# -*- coding:utf-8 -*-

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from lxml import etree
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
from pymongo import MongoClient

"""
专利检索及分析
http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uiIndex.shtml
账号：gdygod2 密码 gdy198622
"""


# 初始化
def init_driver(url):
    firefox_options = Options()
    # fire_options.add_argument('--headless') # 无头模式
    firefox_options.add_argument('--disable-gpu')
    firefox_options.set_preference("general.useragent.override", 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36')  # 修改请求头，伪装浏览器型号
    # driver = webdriver.Chrome(chrome_options=chrome_options) # 已经设置PATH环境变量
    # 未在PATH环境变量中设置，需要设置驱动可执行路径
    driver = webdriver.Firefox(executable_path='D:\\webdriver\\geckodriver.exe', options=firefox_options)
    driver.maximize_window()  # 浏览器最大化
    driver.get(url)
    return driver


# 获取页面url
def get_url(drive):
    # 设置等待
    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.ID, "j_username"))).send_keys("testuser6666")
    time.sleep(1)
    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.ID, "j_password_show"))).send_keys("6666testuser")
    driver.find_element_by_css_selector('[class="btn btn-login"]').click()
    # 搜索内容
    WebDriverWait(driver, 50).until(
        EC.presence_of_element_located((By.ID, "search_input"))).send_keys("大数据")
    driver.find_element_by_id('btn_generalSearch').click()
    while True:
        WebDriverWait(driver, 50).until(
            EC.presence_of_element_located((By.ID, "search_result_former")))
        selector = etree.HTML(driver.page_source)

        xpath = selector.xpath('//div[@class="list-container"]/ul/li')
        count = 0
        for i in xpath:
            dict_data = dict()
            dict_data['title'] = "".join(i.xpath('.//div[@class="item-header clear"]/h1//text()')).replace("\t", "").strip()
            dict_data['sqh'] = i.xpath('.//div[@class="item-content-body left"]/p[1]/text()')[0]  # 申请号
            dict_data['sq_rq'] = i.xpath('.//div[@class="item-content-body left"]/p[2]/a/text()')[0]  # 申日期
            dict_data['gk_hao'] = i.xpath('.//div[@class="item-content-body left"]/p[3]/text()')[0]  # 公开（公告）号
            dict_data['gk_rq'] = i.xpath('.//div[@class="item-content-body left"]/p[4]/a/text()')[0]  # 公开（公告）日
            dict_data['ipc'] = "".join(i.xpath('.//div[@class="item-content-body left"]/p[5]/span//text()')) \
                .replace("\t", "").replace(" ", "")  # IPC分类号
            dict_data['sq_ren'] = i.xpath('.//div[@class="item-content-body left"]/p[6]/span/a/text()')[0]  # 申请（专利权）人
            dict_data['fmr'] = "".join(i.xpath('.//div[@class="item-content-body left"]/p[7]/span//text()')) \
                .replace("\t", "").replace(" ", "")  # 发明人
            dict_data['dl_r'] = "".join(i.xpath('.//div[@class="item-content-body left"]/p[8]/text()'))  # 代理人
            dict_data['dl_jg'] = "".join(i.xpath('.//div[@class="item-content-body left"]/p[9]/text()'))  # 代理机构
            dict_data['gk'] = i.xpath('.//div[@class="btn-group left clear"]/a[1]/text()')[0]  # 公开
            dict_data['tz'] = i.xpath('.//div[@class="btn-group left clear"]/a[2]/text()')[0]  # 同族
            dict_data['yz'] = i.xpath('.//div[@class="btn-group left clear"]/a[3]/text()')[0]  # 引证
            dict_data['by'] = i.xpath('.//div[@class="btn-group left clear"]/a[4]/text()')[0]  # 被引
            time.sleep(1)
            # # 法律状态
            # driver.find_elements_by_xpath('//div[@class="btn-group clear"]/a[5]')[count].click()
            # root_lawResult = etree.HTML(driver.page_source)
            # tag_count = 1
            # for l in root_lawResult.xpath('//table[@id="lawResult"]/tbody/tr'):
            #     dict_data['law_no_' + str(tag_count)] = l.xpath('./td[1]/text()')[0]
            #     dict_data['law_rq_' + str(tag_count)] = l.xpath('./td[2]/text()')[0]
            #     dict_data['law_hy_' + str(tag_count)] = l.xpath('./td[3]/text()')[0]
            #     tag_count += 1
            # time.sleep(1)
            # # 关闭
            # driver.find_elements_by_xpath('//button[@class="ui-dialog-close"]')[0].click()

            # # 详情
            # driver.find_elements_by_xpath('//div[@class="btn-group clear"]/a[1]')[count].click()
            # time.sleep(0.5)
            # all_handles = driver.window_handles
            # now_handle = driver.current_window_handle
            # for handle in all_handles:
            #     if handle != now_handle:
            #         driver.switch_to.window(handle)  # 切换新打开窗口
            #         WebDriverWait(driver, 50).until(
            #             EC.presence_of_element_located((By.CLASS_NAME, "content")))
            #         selector = etree.HTML(driver.page_source)
            #         # 摘要
            #         dict_data['desc'] = "".join(selector.xpath('//td[@class="content"]//text()')).replace("\n", "").strip()
            #         driver.close()
            # print(str(dict_data))
            # driver.switch_to.window(all_handles[0])
            # 行数
            count += 1
            # insertItem("国家专利1", dict_data)
        time.sleep(3)
        try:
            # 点击下一页
            driver.find_element_by_xpath('//div[@class="page_bottom"]//a[contains(text(),"下一页")]').click()
            time.sleep(3)
        except:
            close_driver(driver)
            break

def insertItem(tableName, data):
    my_set = db[tableName]
    my_set.insert_one(data)


def close_driver(driver):
    driver.quit()

if __name__ == '__main__':
    conn = MongoClient('127.0.0.1', 27017)
    db = conn["Test"]
    url = "http://pss-system.cnipa.gov.cn/sipopublicsearch/portal/uilogin-forwardLogin.shtml"
    driver = init_driver(url)
    get_url(driver)

